package com.coursehub.shared.transaction;

import lombok.Data;

import java.time.LocalDateTime;

/**
 * 分布式事务执行结果
 */
@Data
public class TransactionResult {
    
    /**
     * 是否成功
     */
    private final boolean success;
    
    /**
     * 结果消息
     */
    private final String message;
    
    /**
     * 错误代码
     */
    private final String errorCode;
    
    /**
     * 执行时间
     */
    private final LocalDateTime executeTime;
    
    /**
     * 异常信息
     */
    private final Throwable exception;
    
    private TransactionResult(boolean success, String message, String errorCode, Throwable exception) {
        this.success = success;
        this.message = message;
        this.errorCode = errorCode;
        this.exception = exception;
        this.executeTime = LocalDateTime.now();
    }
    
    /**
     * 创建成功结果
     */
    public static TransactionResult success(String message) {
        return new TransactionResult(true, message, null, null);
    }
    
    /**
     * 创建成功结果（默认消息）
     */
    public static TransactionResult success() {
        return success("事务执行成功");
    }
    
    /**
     * 创建失败结果
     */
    public static TransactionResult failure(String message) {
        return new TransactionResult(false, message, "TRANSACTION_FAILED", null);
    }
    
    /**
     * 创建失败结果（带错误代码）
     */
    public static TransactionResult failure(String message, String errorCode) {
        return new TransactionResult(false, message, errorCode, null);
    }
    
    /**
     * 创建失败结果（带异常）
     */
    public static TransactionResult failure(String message, Throwable exception) {
        return new TransactionResult(false, message, "TRANSACTION_EXCEPTION", exception);
    }
    
    /**
     * 创建失败结果（带错误代码和异常）
     */
    public static TransactionResult failure(String message, String errorCode, Throwable exception) {
        return new TransactionResult(false, message, errorCode, exception);
    }
    
    /**
     * 检查是否成功
     */
    public boolean isSuccess() {
        return success;
    }
    
    /**
     * 检查是否失败
     */
    public boolean isFailure() {
        return !success;
    }
    
    /**
     * 获取错误信息
     */
    public String getErrorMessage() {
        if (success) {
            return null;
        }
        
        StringBuilder sb = new StringBuilder();
        if (message != null) {
            sb.append(message);
        }
        
        if (errorCode != null) {
            sb.append(" [错误代码: ").append(errorCode).append("]");
        }
        
        if (exception != null) {
            sb.append(" [异常: ").append(exception.getMessage()).append("]");
        }
        
        return sb.toString();
    }
    
    @Override
    public String toString() {
        return String.format("TransactionResult{success=%s, message='%s', errorCode='%s', executeTime=%s}",
                success, message, errorCode, executeTime);
    }
}